package com.Web.Servlet;

import com.Web.Person.VO.GenderCountVO;
import com.Web.util.JDBCUtil;
import com.Web.util.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/echarts")
public class EChartServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<GenderCountVO> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "SELECT COUNT(*) AS 'value',gender AS 'name' FROM student GROUP BY gender";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()) {
                int value = resultSet.getInt("value");
                String name = resultSet.getString("name");
                GenderCountVO genderCountVO = new GenderCountVO(name, value);
                list.add(genderCountVO);
            }
            System.out.println(list);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection,preparedStatement,resultSet);
        }
        JSONUtil.toJSON(resp,list);
//        resp.setContentType("text/html;charset=UTF-8");
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.writeValue(resp.getWriter(),list);
    }
}
